// pages/category/index.js
const api = require('../../utils/request')
const utils = require('../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    category:[],
    activeKey: 0,
    showList:[],
    scroll_height: 0,
    loading:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let windowHeight = wx.getSystemInfoSync().windowHeight // 屏幕的高度
    let windowWidth = wx.getSystemInfoSync().windowWidth // 屏幕的宽度
    this.setData({
      scroll_height: windowHeight * 750 / windowWidth - 75 - 30
    })
    this.getCategory()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  gotoSearch(){
    wx.navigateTo({
      url: '/pages/search/index'
    })
  },
  addToCart(event){
    // 没登录就跳转登录页面
    if(utils.loginNow()){
       // res.currentTarget.dataset.item 
      const gid = event.currentTarget.dataset.gid 
      wx.showLoading({
        title: '正在加入购物车',
      })
      api.post('/user/cart/add',{count:1,idGoods: gid,idSku: ""}).then(_=>{
        wx.hideLoading();
        wx.showToast({
          title: '加入购物车成功',
        })
      })
    }

    
   
  },
  getCategory(){
    api.get('/category/list').then(res=>{
      console
      this.setData({
        category: res
      })
      this.getCateoryList(this.data.activeKey)
    })
  },
  sidebarChange(event){
    this.setData({
      activeKey:event.detail
    })
    this.getCateoryList(event.detail)
  },
  getCateoryList(ac_id){
    this.setData({
      loading: true
    })
    const oneCategory = this.data.category[ac_id]
    if(oneCategory.list){
      this.setData({
        showList:oneCategory.list,
        loading: false
      })
      return;
    }
    api.get('/goods/queryGoods?page=1&limit=50&idCategory='+oneCategory.id)
    .then(res => {
      if (res.total > 0) {
        let goodsList = res.records
        for (let i = 0; i < goodsList.length; i++) {
          goodsList[i].price = utils.formatPrice(goodsList[i].price)
          goodsList[i].imgUrl = utils.fileMgrUrl + goodsList[i].pic
        }
        oneCategory['list']=goodsList
        this.setData({
          showList:goodsList,
          loading: false
        })
      }else{
        this.setData({
          loading: false
        })
      }
      
    })
  },
  gotoGoodsDetail(event){
    console.log(event)
    let id = event.currentTarget.dataset.gid;
    wx.navigateTo({
      url: '/pages/goods/index?id='+id,
    })
  }
})